//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import type { NodeInfo } from '@/api/project_dataview';
import ProjectNodeWrap from '../ProjectNodeWrap';
import { Button, Descriptions, Space, Tag } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react';
import { useDataViewStores } from '@/pages/DataView/store';
import { get_requirement, type GetRequirementResponse } from "@/api/project_requirement";
import { get_session } from '@/api/user';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import UserPhoto from '@/components/Portrait/UserPhoto';
import RequirementDetailModal from '@/pages/Project/Requirement/RequirementDetailModal';

const RefRequireMentNode = (props: NodeProps<NodeInfo>) => {
    const dataViewStore = useDataViewStores();

    const [dataResponse, setDataResponse] = useState<GetRequirementResponse | null>(null);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [requirementTab, setRequirementTab] = useState<"detail" | "issue" | "fourq" | "kano" | "event" | "comment">("detail");

    const loadDataResponse = async () => {
        const sessionId = await get_session();
        const res = await get_requirement({
            session_id: sessionId,
            project_id: dataViewStore.projectStore.projectId,
            requirement_id: props.data.node_data.RefTargetId ?? "",
        });
        setDataResponse(res);
    }

    useEffect(() => {
        loadDataResponse();
    }, []);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.RequirementNotice?.UpdateRequirementNotice != undefined && notice.RequirementNotice.UpdateRequirementNotice.requirement_id == props.data.node_data.RefTargetId) {
                loadDataResponse();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <ProjectNodeWrap title="项目需求" nodeData={props} canChangeBgColor
            extraButtonList={[
                <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    loadDataResponse();
                }} />
            ]}>
            {dataResponse != null && (
                <>
                    {dataResponse.code != 0 && <span style={{ color: "red" }}>{dataResponse.err_msg}</span>}
                    {dataResponse.code == 0 && (
                        <div>
                            <a style={{ fontSize: "20px", fontWeight: 700 }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowDetailModal(true);
                            }}>{dataResponse.requirement.base_info.title}</a>

                            <Descriptions column={1}>
                                <Descriptions.Item label="状态">{dataResponse.requirement.closed ? "关闭" : "打开"}</Descriptions.Item>
                                <Descriptions.Item label="标签">
                                    <Space style={{ flexWrap: "wrap" }}>
                                        {dataResponse.requirement.tag_info_list.map(tag => (
                                            <Tag key={tag.tag_id} style={{ backgroundColor: tag.bg_color }}>{tag.tag_name}</Tag>
                                        ))}
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="创建人">
                                    <Space>
                                        <UserPhoto logoUri={dataResponse.requirement.create_logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                                        {dataResponse.requirement.create_display_name}
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="关注">
                                    <Space style={{ flexWrap: "wrap" }}>
                                        {dataResponse.requirement.watch_user_list.map(watchUser => (
                                            <Space key={watchUser.member_user_id}>
                                                <UserPhoto logoUri={watchUser.logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                                                {watchUser.display_name}
                                            </Space>
                                        ))}
                                    </Space>
                                </Descriptions.Item>
                            </Descriptions>
                        </div>
                    )}
                </>
            )}
            {dataResponse != null && dataViewStore.projectStore.projectInfo != null && showDetailModal && (
                <RequirementDetailModal projectInfo={dataViewStore.projectStore.projectInfo} tagList={dataViewStore.projectStore.tagList}
                    myUserId={dataViewStore.projectStore.myUserId}
                    requirementId={props.data.node_data.RefTargetId ?? ""} requirementTab={requirementTab}
                    onClose={() => {
                        setShowDetailModal(false);
                        setRequirementTab("detail");
                    }}
                    onChange={newTab => setRequirementTab(newTab)}
                    onClickTask={() => {
                        //do nothing
                    }} />
            )}

        </ProjectNodeWrap>
    )
};

export default observer(RefRequireMentNode);
